<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace App\Service;

use App\Constants\ErrorCode;
use App\Exception\BusinessException;
use App\Model\Answer;
use App\Service\Dao\AnswerDao;
use App\Service\Dao\QuestionDao;
use App\Service\Dao\UserDao;
use Hyperf\Di\Annotation\Inject;
use HyperfX\Utils\Service;

class AnswerService extends Service
{
    /**
     * @Inject
     * @var AnswerDao
     */
    protected $dao;

    public function index(int $questionId, int $offset, int $limit)
    {
        return $this->dao->find($questionId, $offset, $limit);
    }

    /**
     * @param $input = [
     *     'question_id' => 0, // 问题ID
     *     'summary' => '', // 回答详情
     * ]
     */
    public function publish(int $id, int $userId, array $input)
    {
        $question = di()->get(QuestionDao::class)->firstCache($input['question_id'], true);
        $user = di()->get(UserDao::class)->firstCache($userId, true);
        if (! $user->isLegal()) {
            throw new BusinessException(ErrorCode::OPERATION_INVALID, '非律师不允许回答');
        }

        if ($id > 0) {
            $model = $this->dao->firstCache($id);
            if ($model->user_id !== $userId) {
                throw new BusinessException(ErrorCode::OPERATION_INVALID);
            }
        } else {
            $model = new Answer();
            $model->user_id = $userId;
            $model->question_id = $question->id;
        }

        $model->summary = $input['summary'];
        $model->save();

        if ($id === 0) {
            $question->increment('answer_count');
        }

        return $model;
    }
}
